<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <el-button type="primary" @click="addPlayVisible = true"
        >添加放映</el-button
      >
      <el-upload
        class="upload-demo"
        action="http://localhost:9999/filmplay/upload"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :headers="{ token: token }"
      >
        <el-button size="large" type="primary">导入</el-button>
      </el-upload>
      <el-button type="primary" @click="addPlayVisible = true">导出</el-button>
      <el-table
        :data="playList"
        :border="true"
        stripe
        :show-summary="true"
        :summary-method="getSummaries"
      >
        <el-table-column type="index" :resizable="false"></el-table-column>
        <el-table-column prop="filmName" label="电影名称"></el-table-column>
        <el-table-column
          prop="hallName"
          label="所在影厅"
          :resizable="false"
        ></el-table-column>
        <el-table-column
          prop="price"
          label="单价（￥）"
          :resizable="false"
        ></el-table-column>
        <el-table-column
          prop="playOpenTime"
          label="开始时间"
          :resizable="false"
        ></el-table-column>
        <el-table-column label="操作" :resizable="false">
          <template v-slot="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.managerId)"
              >编辑</el-button
            >

            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removePlayById(scope.row.playId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="prev, pager, next, jumper,total,sizes"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加放映"
      v-model:visible="addPlayVisible"
      width="25%"
      @close="addDialogClose"
    >
      <!-- 主体 -->
      <el-form :model="addForm" ref="addFormRef" label-width="90px">
        <el-form-item label="电影名称" prop="filmName">
          <el-dropdown placement="bottom" @command="clickFilm">
            <el-input v-model="filmName"></el-input>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in filmList"
                :key="item.filmId"
                :command="item"
                >{{ item.filmName }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item label="影厅名称" prop="hallName">
          <el-input
            style="width: 206.7px"
            disabled
            v-model="addForm.hallName"
          ></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="addForm.price" placeholder="默认单位￥"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="playOpenTime">
          <el-date-picker
            :picker-options="pickerOptions"
            type="datetime"
            v-model="addForm.playOpenTime"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="playFinishTime">
          <el-date-picker
            :picker-options="pickerOptions"
            type="datetime"
            v-model="addForm.playFinishTime"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <!--底部  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPlayVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPlay">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      playList: [],
      queryInfo: {
        query: "",
        //当前显示的页码
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      addPlayVisible: false,
      addForm: {
        hallName: "1号厅",
      },
      filmList: [],
      filmName: "",
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "明天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      token: localStorage.getItem("token"),
    };
  },
  methods: {
    async getPlayList() {
      const { data: res } = await this.$http.get(
        "common/filmplay/getTotleList",
        { params: this.queryInfo }
      );
      console.log(res);
      if (res.code != 200) {
        return this.$message.error(res.message);
      } else {
        this.playList = res.data.value;
        this.total = res.data.total;
        var pageCount = Math.ceil(this.total / this.queryInfo.pagesize);
        if (this.queryInfo.pagenum > pageCount) {
          this.queryInfo.pagenum = pageCount;
          this.getPlayList();
        }
      }
    },
    addDialogClose() {},
    addPlay() {
      this.toPlay();
    },
    async toPlay() {
      this.addForm.playOpenTime = this.dateFormat(
        new Date(this.addForm.playOpenTime)
      );
      this.addForm.playFinishTime = this.dateFormat(
        new Date(this.addForm.playFinishTime)
      );

      const { data: res } = await this.$http.post(
        "/common/filmplay/addPlay",
        this.addForm
      );
      console.log(res);
      if (res.code != 200) {
        return this.$message.error(res.message);
      } else {
        this.addPlayVisible = false;
        this.getPlayList();
      }
    },
    clickFilm(command) {
      this.addForm.filmId = command.filmId;
      this.filmName = command.filmName;
    },
    async getFilmList() {
      const { data: res } = await this.$http.get(
        "/common/filminfo/getListPlaying"
      );
      console.log(res);
      if (res.code != 200) {
        return this.$message.error(res.message);
      } else {
        var temp = res.data;
        temp.forEach((element) => {
          this.filmList.push(element);
        });
      }
    },

    dateFormat(date) {
      var year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      // 拼接
      return year + "-" + month + "-" + day + " " + h + m + s;
    },
    async removePlayById(id) {
      const res = await this.$confirm("永久删除，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err); //点取消会报错，捕获
      if (res != "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: result } = await this.$http.delete(
        "common/filmplay/removePlay",
        { params: { id: id } }
      );
      if (result.code != 200) {
        return this.$message.error(result.message);
      }
      this.$message.success(result.message);
      this.getPlayList();
    },

    //监听pageSize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getPlayList();
    },
    //监听页码改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getPlayList();
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        console.log(index, column);
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += " 元";
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },
    uploadSuccess() {
      alert("success");
    },
  },
  created() {
    this.getPlayList();
    this.getFilmList();
  },
};
</script>

<style lang="less" scoped>
.el-dropdown-menu {
  width: 206.7px;
}
.upload-demo {
  display: inline-block;
  margin: 0 10px;
}
</style>